package com.gxc.aop;

import com.gxc.utils.ThrowableMessageUtil;
import java.lang.reflect.Method;
import java.time.Instant;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;

/**
 * 测试 aspect.
 *
 * @author 宫新程
 * @since 2018/12/18 10:02 AM
 */
@Slf4j
@Aspect
@Configuration
public class MyAspect {

  /** 切入点. */
  @Pointcut("@annotation(com.gxc.annotation.MyAnnotation.*)")
  public void controllerPointCut() {}

  /** 通知. */
  //  @Around("controllerPointCut()")
  @Around("execution(* com.gxc.controller..*.*(..))")
  public Object around(ProceedingJoinPoint proceedingJoinPoint) {
    MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
    Method method = signature.getMethod();

    log.info("前置通知...{}", method.getName());
    long start = Instant.now().toEpochMilli();
    Object proceed = null;
    try {
      proceed = proceedingJoinPoint.proceed();
    } catch (Throwable throwable) {
      log.error("{}方法出现异常...异常信息：{}", method.getName(), ThrowableMessageUtil.getMessage(throwable));
    }
    long end = Instant.now().toEpochMilli();
    log.info("后置通知...{}, 执行时间：「{}」", method.getName(), (end - start));

    return proceed;
  }
}
